#!/usr/bin/env node

import fs from 'fs'
import path from 'path'

/**
 * 清理console.log语句的脚本
 * 用于生产环境前的代码清理
 */

// 需要清理的文件扩展名
const extensions = ['.vue', '.ts', '.js']

// 需要清理的目录
import { fileURLToPath } from 'url'
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
const srcDir = path.join(__dirname, '../src')

// console语句的正则表达式
const consoleRegex = /^\s*console\.(log|debug|info|warn|error)\(.*\);\s*$/gm

// 以//开头的注释形式的console
const commentConsoleRegex = /^\s*\/\/\s*console\.(log|debug|info|warn|error)\(.*\);\s*$/gm

let filesProcessed = 0
let consoleStatementsRemoved = 0

function cleanFile(filePath) {
  try {
    const content = fs.readFileSync(filePath, 'utf8')
    let newContent = content

    // 计算移除的console语句数量
    const matches = content.match(consoleRegex) || []
    const commentMatches = content.match(commentConsoleRegex) || []

    if (matches.length > 0 || commentMatches.length > 0) {
      // 移除console语句
      newContent = newContent.replace(consoleRegex, '')
      // 移除注释掉的console语句
      newContent = newContent.replace(commentConsoleRegex, '')

      // 移除多余的空行
      newContent = newContent.replace(/\n\s*\n\s*\n/g, '\n\n')

      fs.writeFileSync(filePath, newContent, 'utf8')

      console.log(`清理文件: ${filePath}`)
      console.log(`  移除console语句: ${matches.length}条`)
      if (commentMatches.length > 0) {
        console.log(`  移除注释console语句: ${commentMatches.length}条`)
      }

      consoleStatementsRemoved += matches.length + commentMatches.length
    }

    filesProcessed++
  } catch (error) {
    console.error(`处理文件失败 ${filePath}:`, error.message)
  }
}

function walkDirectory(dir) {
  try {
    const files = fs.readdirSync(dir)

    for (const file of files) {
      const filePath = path.join(dir, file)
      const stat = fs.statSync(filePath)

      if (stat.isDirectory()) {
        // 跳过node_modules和dist目录
        if (file !== 'node_modules' && file !== 'dist' && file !== '.git') {
          walkDirectory(filePath)
        }
      } else if (stat.isFile()) {
        const ext = path.extname(file)
        if (extensions.includes(ext)) {
          cleanFile(filePath)
        }
      }
    }
  } catch (error) {
    console.error(`读取目录失败 ${dir}:`, error.message)
  }
}

console.log('开始清理console语句...')
console.log(`扫描目录: ${srcDir}`)

walkDirectory(srcDir)

console.log('\n清理完成!')
console.log(`处理文件数: ${filesProcessed}`)
console.log(`移除console语句总数: ${consoleStatementsRemoved}`)

if (consoleStatementsRemoved > 0) {
  console.log('\n建议: 在开发过程中使用debugger或开发工具进行调试，避免在代码中留下console语句')
}
